const Feedback = require('../models/Feedback');
const User = require('../models/User');
const { getTimestamp, getTwoDigits, formatObject,reverseFormatObject } = require('../utils/common');
const { sendResponse, sendListResponse } = require('../utils/response');
const { Op } = require('sequelize');

// 提交反馈
exports.createFeedback = async (req, res) => {
  const { createId, feedbackType, content, contactInfo } = req.body;

  try {
    const id = "189" + getTimestamp() + getTwoDigits();
    await Feedback.create(reverseFormatObject({
      id,
      createId,
      feedbackType,
      content,
      contactInfo,
      createdTime: new Date(),
      updatedTime: new Date(),
      status: 1
    }));
    sendResponse(res, 200, '反馈提交成功');
  } catch (error) {
    console.error('提交反馈失败:', error);
    sendResponse(res, 500, '反馈提交失败');
  }
};

// 获取反馈列表
exports.getFeedbacks = async (req, res) => {
  const { createId, solveId, status, feedbackType, page = 1, pageSize = 10, keyword } = req.query;

  try {
    const where = {};
    if (createId) {
      where.create_id = createId;
    }
    if (status) {
      where.status = status;
    }
    if (feedbackType) {
      where.feedback_type = feedbackType;
    }
    if (solveId) {
      where.solve_id = solveId;
    }
    if (keyword) {
      where.content = {
        [Op.like]: `%${keyword}%`
      };
    }

    const { count, rows } = await Feedback.findAndCountAll({
      where,
      order: [['created_time', 'DESC']],
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['user_id', 'nickname'],
          required: false
        },
        {
          model: User,
          as: 'solver',
          attributes: ['user_id', 'nickname'],
          required: false
        }
      ]
    });

    // 处理返回数据
    const feedbacks = rows.map(item => {
      const data = item.toJSON();
      return formatObject({
        ...data,
        createName: data.creator?.nickname || '',
        solveName: data.solver?.nickname || ''
      });
    });

    sendListResponse(res, 200, "获取反馈列表成功", feedbacks, count);
  } catch (error) {
    console.error('获取反馈列表失败:', error);
    sendResponse(res, 500, '获取反馈列表失败');
  }
};

// 更新反馈状态
exports.updateFeedbackStatus = async (req, res) => {
  const { id, status, solveId,remark } = req.body;

  try {
    console.log("id=>",id,typeof id)
    const feedback = await Feedback.findByPk(id);
    if (!feedback) {
      return sendResponse(res, 500, '反馈不存在');
    }

    await feedback.update(reverseFormatObject({
      status,
      solveId,
      remark,
      updatedTime: new Date()
    }));

    sendResponse(res, 200, '反馈状态更新成功');
  } catch (error) {
    console.error('更新反馈状态失败:', error);
    sendResponse(res, 500, '更新反馈状态失败');
  }
};

// 获取反馈详情
exports.getFeedbackDetail = async (req, res) => {
  try {
    const { id } = req.params;

    const feedback = await Feedback.findOne({
      where: { id },
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['user_id', 'nickname'],
          required: false
        },
        {
          model: User,
          as: 'solver',
          attributes: ['user_id', 'nickname'],
          required: false
        }
      ]
    });

    if (!feedback) {
      return sendResponse(res, 404, '反馈不存在');
    }
    const data = feedback.toJSON();
    const result = formatObject({
      ...data,
      createName: data.creator?.nickname || '',
      solveName: data.solver?.nickname || ''
    });
    sendResponse(res, 200, '', result);
  } catch (error) {
    console.error('获取反馈详情失败:', error);
    sendResponse(res, 500, '获取反馈详情失败');
  }
};